#!/usr/bin/python

from __future__ import with_statement
from cStringIO import StringIO
#from contrib.sphinxapi import *
import sqlalchemy as sa
from Queue import Queue
from threading import Thread
import threading
from datetime import datetime, date,timedelta
from time import strftime
import re, traceback, calendar, time, sys
import string
#from local
from lib.database_qzone import Database, g_pagesize

from lib.utils import sanitizestring, transcode3, transcode5
from lib.qqaddr import getProvinceIdx, getCityIdx, getCountryIdx

# type obj
class scheme:
    docid = 'seq'
    type = 'type'

csft_string_const = 'csft_string_const'
csft_string_fulltext = 'csft_string_fulltext'
csft_number = 'csft_number'
csft_float = 'csft_float'
csft_boolean = 'csft_boolean'
csft_timestamp = 'csft_timestamp'
csft_list = 'csft_list'
csft_file_pdf = 'csft_file_pdf'
csft_file_office = 'csft_file_office'

class QzoneBlog:
    def __init__(self, O):
        self.include_info = True
        self.i = 0

        self.seq = -1
        self.content = ''
        self.title = ''
        self.authorseq = -1
        self.sex = 0
        self.age = 0
        self.marriage = 0
        self.country = 0
        self.province = 0
        self.city = 0
        self.qqid= 0
        self.dal = Database()

        self.cursor = 0
        self.workingset = []
        self.onlinestatus=0    #offline 1 unknow 2 online 3 
        #for k in O.keys():
        #    print k, O[k] 

    def getScheme(self):
        if self.include_info:
            return {'seq': {'seq': True},
                'title': {'type': csft_string_fulltext},
                'content': {'type': csft_string_fulltext},
                'country': {'type': csft_number},
                'province': {'type': csft_number},
                'city': {'type': csft_number},
                'sex': {'type': csft_number},
                'age': {'type': csft_number},
                'marriage': {'type': csft_number},
                'qqid': {'type': csft_number},
                'authorseq': {'type': csft_number},
                'onlinestatus':{'type':csft_number}}
        else:
            return {'seq': {'seq': True},
                'title': {'type': csft_string_fulltext},
                'content': {'type': csft_string_fulltext},
                'authorseq': {'type': csft_number}}

    def Connected(self):
        pass

    def NextDocument(self):
        while True:
            barrier = len(self.workingset) if (len(self.workingset) < g_pagesize) else g_pagesize
            if self.cursor >= barrier:
                self.workingset = self.dal._queryBlog(self.seq)
                if not self.workingset:
                    return False
                else:
                    self.i += 1
                    self.cursor = 0

            b = self.workingset[self.cursor]
            [blog_id, authorid, title, time, num_comment, num_read, content, plaintext, cat_id, cat_name, seq] = b
            blog_id = str(blog_id)
            authorid = str(authorid)
            title = title.encode('utf-8') if (title and isinstance(title, unicode)) else title
            num_comment = int(num_comment)
            num_read = int(num_read)
            content = content.encode('utf-8') if (content and isinstance(content, unicode)) else content
            plaintext = plaintext.encode('utf-8') if (plaintext and isinstance(plaintext, unicode)) else plaintext
            cat_id = int(cat_id)
            cat_name = cat_name.encode('utf-8') if (cat_name and isinstance(cat_name, unicode)) else cat_name
            seq = int(seq)

            self.cursor += 1
            self.qqid=int(authorid)
            self.onlinestatus=0   #offline 1 unknow 2 online 3 
            oneuser = self.dal._queryOneUser(authorid)
            if oneuser:
                self.authorseq = int(oneuser[7])
                profile = self.dal._queryOneProfile(str(oneuser[0]))
                sex = profile[1].encode('utf-8') if (profile[1] and isinstance(profile[1], unicode)) else profile[1]
                country = profile[5].encode('utf-8') if (profile[5] and isinstance(profile[5], unicode)) else profile[5]
                prov = profile[6].encode('utf-8') if (profile[6] and isinstance(profile[6], unicode)) else profile[6]
                city = profile[7].encode('utf-8') if (profile[7] and isinstance(profile[7], unicode)) else profile[7]
                if self.include_info:
                  if profile:
                    if sex == 'male':
                        self.sex = 1
                    elif sex == 'fema':
                        self.sex = 2
                    else:
                        self.sex = 0
                    if profile[2] > 0 and profile[2] < 150:
                        self.age = int(profile[2])
                    else:
                        self.age = 0
                    if profile[11] == 1 or profile[11] == 2 or profile[11] == 3:
                        self.marriage = int(profile[11])
                    else:
                        self.marriage = 0
                    self.country = getCountryIdx(country)
                    self.province = getProvinceIdx(prov)
                    self.city = getCityIdx(prov, city)
                  else:
                    self.sex = 0
                    self.age = 0
                    self.marriage = 0
                    self.country = 0
                    self.province = 0
                    self.city = 0
            else:
                print blog_id + " " + str(seq) + " didn't find authorid " + authorid
                continue
            self.seq = seq
            self.title = title
            self.content = plaintext
            if self.title == '':
                continue
            #print self.seq, self.content, self.title, self.authorseq, self.sex, self.age, self.marriage, self.country, self.province, self.city, self.qqid, self.cursor
            return True

    def OnBeforeIndex(self):
        pass

    def OnAfterIndex(self):
        pass

    def OnIndexFinished(self):
        del self.dal
        self.dal = None

def Test():
    Qz=QzoneBlog(None)
    Qz.test(100032)
    Qz.test(100104)
#Test()
